package cn.yj.frame.netty;

import cn.yj.frame.protrol.RpcProtocol;
import cn.yj.frame.spring.BeanUtils;
import cn.yj.register.RegisterConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * @author 永健
 * @since 2022-01-17 16:53
 */
public class NettyServer extends AbstractNettyServer {

    private static final Logger log = LoggerFactory.getLogger(NettyServer.class);

    private static Channel serverChannel;

    public static void closeServer(){
        if (serverChannel!=null){
            serverChannel.close();
        }
    }

    @Override
    void run(InetSocketAddress inetSocketAddress) {
        EventLoopGroup parentGroup = new NioEventLoopGroup(1);
        EventLoopGroup childGroup = new NioEventLoopGroup(10);
        try {
            ServerBootstrap serverBootstrap =
                    new ServerBootstrap().group(parentGroup, childGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    // 编码解码
                    socketChannel.pipeline().addLast("encoder", new ObjectEncoder());
                    // 解码处理器
                    socketChannel.pipeline().addLast("decoder", new ObjectDecoder(1024,
                            ClassResolvers.cacheDisabled(this.getClass().getClassLoader())));

                    socketChannel.pipeline().addLast(new IdleStateHandler(3, 3, 3, TimeUnit.SECONDS));

                    // 消息处理器-读取
                    socketChannel.pipeline().addLast(new SimpleChannelInboundHandler<Object>() {
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                            super.exceptionCaught(ctx, cause);
                            cause.printStackTrace();
                            log.info("netty => 连接异常");
                        }

                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            super.channelActive(ctx);
                            log.info("netty => 客户端连接");
                        }

                        @Override
                        protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {

                            Object result;
                            if (o instanceof RpcProtocol) {
                                RpcProtocol protocol = (RpcProtocol) o;
                                String beanName = protocol.getBeanName();
                                String methodName = protocol.getMethodName();
                                Object[] methodParams = protocol.getMethodParams();
                                try {
                                    Object bean = BeanUtils.getBean(beanName);
                                    Method declaredMethod = bean.getClass().getDeclaredMethod(methodName,
                                            protocol.getMethodParamsType());
                                    result = declaredMethod.invoke(bean, methodParams);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    result = "服务器异常,找不到对应的服务";
                                }
                                channelHandlerContext.channel().writeAndFlush(result);
                            }

                        }
                    });
                }

            }).localAddress(inetSocketAddress).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(64 * 1024, 128 * 1024));
            ChannelFuture f = serverBootstrap.bind(inetSocketAddress.getPort()).sync();
            serverChannel=f.channel();
            serverChannel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            parentGroup.shutdownGracefully();
            childGroup.shutdownGracefully();
        }
    }

}
